package com.itruth.module.share;

import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.LinearGradient;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.itruth.base.BaseActivity;
import com.itruth.base.LocalNotice;
import com.itruth.base.NoticeCallback;
import com.itruth.data.dao.ShareDao;
import com.itruth.data.entity.ResponseData;
import com.itruth.data.entity.ShareEntity;
import com.itruth.data.entity.UserData;
import com.itruth.main.R;
import com.itruth.util.CommonUtil;
import com.itruth.util.Constant;
import com.itruth.util.HttpUtil;
import com.itruth.util.ThreadPool;

public class ShareActivity extends BaseActivity {

	/**
	 * 请求分享数据成功
	 */
	private static final int REQ_SHAREDATA_SUCCESS = 0x01;
	/**
	 * 初始化页面，从数据库加载缓存数据完成
	 */
	private static final int LOAD_CACHEDATA_SUCCESS = 0x02;
	
	private List<ShareEntity> shares = null;
	
	private ListView listView;
	
	private ShareAdapter adapter;
	
	/**
	 * 当前请求是否是下拉刷新
	 */
	private boolean pullDownRefresh;
	
	private TextView loadTv;
	
	private LinearLayout loadPb;
	
	@Override
	protected void initData() {
		
		shares = new LinkedList<ShareEntity>();
		
		LocalNotice.getIns().regNotice(LocalNotice.ACTION_QUERY_SHAREDATA, receiver);
		
	}
	
	@Override
	protected void initComposition() {
		setContentView(R.layout.share);
		
		listView = (ListView)findViewById(R.id.listview);
		loadTv = (TextView) findViewById(R.id.tv_load_tag);
		loadPb = (LinearLayout) findViewById(R.id.pb_load_tag);
		
		shares = ShareDao.queryCacheData();
		
		if (shares.size() > 0) {
			UserData.getIns().setShareMinId(shares.get(shares.size() - 1).getServerId());
			loadTv.setVisibility(View.VISIBLE);
		} else {
			loadPb.setVisibility(View.VISIBLE);
			
		}
		
		//距离上次刷新，间隔一定时间后才执行
		pullDownRefresh = true;
		HttpUtil.queryShare(0, true);
		
		adapter = new ShareAdapter(this, shares);
		
		listView.setAdapter(adapter);
		
	}
	
	private Handler handler = new Handler () {
		@Override
		public void handleMessage(Message msg) {
			
			if (REQ_SHAREDATA_SUCCESS == msg.what) {
				
				loadPb.setVisibility(View.GONE);
				loadTv.setVisibility(View.GONE);
				JSONObject json = (JSONObject)msg.obj;
				
				List<ShareEntity> entities = parserJsonData(json);
				
				if (!entities.isEmpty()) {
					
					if (pullDownRefresh) {
						shares.clear();
					}
					shares.addAll(entities);
					//更新当前客户端获取的所有分享数据中最旧数据的id(这条数据在服务器端数据库中的id)
					UserData.getIns().setShareMinId(shares.get(shares.size() - 1).getServerId());
					//缓存最新20条数据
					processShareDataCache();
					
					adapter.setData(shares);
				}
				
			} else if (LOAD_CACHEDATA_SUCCESS == msg.what) {
				//缓存加载完成，加载最新数据
				pullDownRefresh = true;
				HttpUtil.queryShare(0, true);
			}
		}
	};
	
	/**
	 * 处理分享数据的缓存，目前只缓存20条
	 */
	private void processShareDataCache() {
		
		if (pullDownRefresh) {

			ThreadPool.getIns().addTaskToCachePool(new Runnable() {
				
				@Override
				public void run() {
					
					ShareDao.delete();
					
					for (int i = 0; i < shares.size(); i++) {
						ShareDao.insert(shares.get(i));
					}
					
				}
			});
			
			
		}
		
	}
	
	private NoticeCallback receiver = new NoticeCallback() {
		
		@Override
		public void callback(ResponseData data) {
			
			if (Constant.RESPONSE_OK == data.getStatus()) {

				JSONObject json = CommonUtil.getJsonObject(data.getData());
				if (null != json) {
					Message msg = Message
							.obtain(handler, REQ_SHAREDATA_SUCCESS);
					msg.obj = json;
					handler.sendMessage(msg);
				}
			}
			
		}
	};
	
	protected void onDestroy() {
		
		LocalNotice.getIns().cancelNotice(LocalNotice.ACTION_QUERY_SHAREDATA);
		super.onDestroy();
	};
	
	private List<ShareEntity> parserJsonData(JSONObject json) {
		
		List<ShareEntity> entities = new LinkedList<ShareEntity>();
		
		JSONArray jArray = null;
		try {
			jArray = json.getJSONArray("shareData");

			Log.i("lanyan", " " + jArray.length());

			ShareEntity entity = null;
			for (int i = 0; i < jArray.length(); i++) {
				JSONObject obj = jArray.getJSONObject(i);
				entity = new ShareEntity();
				entity.setServerId(obj.getInt("id"));
				entity.setContent(obj.getString("content"));
				entity.setShareTime(obj.getString("shareTime"));
				entity.setAuthor(obj.getString("author"));
				entities.add(entity);
			}
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return entities;
	}
	
}
